<template>
    <div>
        <el-button type="primary" icon="el-icon-plus" @click="addTradmark">添加</el-button>
        <!-- 
            el-table
                data    必须是数组
                border  边框
            el-table-column
                prop            你要渲染的字段
                label           字段的中文解释
                width           对该列的宽度的设置,没有px
                type='index'    在页面当中对应的下标
                align="center"  设置列居中
        -->
        <el-table :data="trademarkList" border style="width: 100%;margin:20px 0">
            <el-table-column prop="id" type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column
                sortable
                prop="tmName"
                v-model="trForm.tmName"
                label="商标名称"
                width="width"
            ></el-table-column>
            <el-table-column sortable prop="logoUrl" label="商标logo" width="width">
                <template slot-scope="{row}">
                    <img :src="row.logoUrl" style="width:80px;height:60px" />
                </template>
            </el-table-column>
            <el-table-column prop="prop" label="操作" width="width">
                <template slot-scope="{row}">
                    <!-- TODO 修改 -->
                    <el-button
                        type="warning"
                        icon="el-icon-edit"
                        size="mini"
                        @click="updateTradeMark(row)"
                    >修改</el-button>
                    <el-button
                        type="danger"
                        icon="el-icon-delete"
                        size="mini"
                        @click="deletetradmark(row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 
        
        -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="getPageList"
            :pager-count="7"
            style="text-align: center;"
            :current-page="page"
            :page-sizes="[3, 5, 8]"
            :page-size="limit"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="total"
        ></el-pagination>

        <!-- 
            添加
                visible 
                    dialogFormVisible   true:表示这个dialog弹出来了
                                        false:关掉了dialog了
        -->
        <el-dialog :title="trForm.id ? '修改商标' : '添加商标'" :visible.sync="dialogFormVisible">
            <el-form style="width:80%" :model="trForm" :rules="rules" ref="trForm">
                <el-form-item prop="tmName" label="商标名称">
                    <el-input autocomplete="off" style="width: 600px;" v-model="trForm.tmName"></el-input>
                </el-form-item>
                <el-form-item prop="logoUrl" label="添加商标" v-model="trForm.logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="/dev-api/admin/product/fileUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="trForm.logoUrl" :src="trForm.logoUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrUpdateSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'Trademark',
    data() {
        const validateTrName = (rule, value, callback) => {
            if (value.length < 2 || value.length > 10) {
                /* 相当于拦截器当中拦 */
                callback(new Error('长度在 2 到 10 个字符'));
            } else {
                callback();
            }
        };
        return {
            page: 1,
            limit: 3,
            trademarkList: [],
            total: 0,


            imageUrl: '',
            /* dialog框设置 */
            dialogFormVisible: false,
            trForm: {
                tmName: "",
                logoUrl: ""
            },
            /* 
                开启规则校验 
                    required        表示必填
                    message         错误提交
                    {}              表示一个校验规则
                    trigger         触发校验的时机
                        校验时机
                            blur        失去焦点的时候校验
                            change      内容改变的时候校验
                            统一处理
                    type            数据类型

                    min 输入的最小长度
                    max 输入的最大长度
            */
            rules: {
                abc: {},
                tmName: [
                    { required: true, message: '请输入商标名称', trigger: 'blur' },
                    // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
                    { validator: validateTrName, trigger: 'blur' }
                ],
                logoUrl: [
                    { required: true, message: '请选择图片' }
                ],
            }
        }
    },
    mounted() {
        this.getPageList();
    },
    methods: {
        /* 发送ajax请求 */
        async getPageList(page = 1) {
            this.page = page
            const result = await this.$API.trademark.getPageList(this.page, this.limit)
            if (result.code == 200) {
                // console.log(result.data);
                this.trademarkList = result.data.records
                this.total = result.data.total
            } else {
                alert("获取数据失败")
            }
        },
        /* 点击下拉的一页显示多少数据 */
        handleSizeChange(size) {
            this.limit = size
            this.getPageList()
        },
        /* 添加图片完成 */
        handleAvatarSuccess(res, file) {
            // console.log(res.data);
            this.trForm.logoUrl = res.data;
        },
        /* 添加图片之前校验图片的格式与大小 */
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        /* 点击确认按钮,又是添加又是修改 */
        addOrUpdateSubmit() {
            this.$refs.trForm.validate(async (valid) => {
                if (valid) {
                    /* 发送ajax */
                    let trademarik = this.trForm
                    const result = await this.$API.trademark.addOrUpdate(trademarik)
                    if (result.code == 200 || result.code === 20000) {
                        this.$message.success("数据添加成功!")

                        this.dialogFormVisible = false;//关闭对话框

                        if (trademarik.id) {
                            this.getPageList(this.page)//修改
                        } else {
                            this.getPageList()
                        }

                    }
                } else {
                    /* 复杂写法 */
                    // this.$message({
                    //     message: '恭喜你，这是一条成功消息',
                    //     type: 'success'
                    // });
                    /* 简单写法 */
                    // this.$message.success("恭喜")
                    this.$message.error("添加或者修改校验失败")
                    // this.$message.warning("错误")
                    return false;
                }
            });
        },

        /* 开始修改操作 */
        updateTradeMark(row) {
            this.dialogFormVisible = true;
            // console.log(row);
            /* 
                深拷贝
                    拷贝的值
                    拷贝的地址
            */
            this.trForm = { ...row };//
            // this.trForm = row;//存储的是地址
        },
        /* 开始删除操作 */
        deletetradmark(row) {
            this.$confirm(`您确定要删除?${row.tmName}吗?`, '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$API.trademark.delete(row.id)
                /* 重新获取数据 */
                this.getPageList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /* 点击添加的按钮 */
        addTradmark() {
            /* 清空的dialog中的数据 */
            this.trForm.tmName = "";
            this.trForm.logoUrl = "";
            this.trForm.id = "";
            this.dialogFormVisible = true;
        }
    }
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>